<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getTrainingDetail, enrollTraining, cancelEnrollment } from "@/api/training";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import ArrowLeft from "@iconify-icons/ep/arrow-left";
import Edit from "@iconify-icons/ep/edit";
import UserPlus from "@iconify-icons/ep/user-plus";
import UserMinus from "@iconify-icons/ep/user-minus";
import dayjs from "dayjs";

defineOptions({
  name: "TrainingDetail"
});

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const trainingId = route.params.id as string;

const trainingDetail = ref({
  id: "",
  title: "",
  description: "",
  category: "",
  categoryText: "",
  instructorId: 0,
  instructorName: "",
  maxStudents: 0,
  currentStudents: 0,
  price: 0,
  originalPrice: 0,
  startTime: "",
  endTime: "",
  duration: 0,
  location: "",
  address: "",
  status: 0,
  statusText: "",
  level: 1,
  levelText: "",
  tags: "",
  coverImage: "",
  content: "",
  requirements: "",
  objectives: "",
  schedule: "",
  materials: "",
  certificate: false,
  remark: "",
  createdAt: "",
  updatedAt: ""
});

// 获取培训详情
async function getDetail() {
  loading.value = true;
  try {
    // 使用模拟数据
    const mockDetail = {
      id: trainingId,
      title: "羽毛球基础培训",
      description: "这是羽毛球基础培训的详细描述，包含了培训的主要内容和目标。通过本次培训，学员将掌握羽毛球的基本技能，包括正确的握拍方式、基本步法、发球技巧、接球技巧等。培训采用理论与实践相结合的方式，确保学员能够快速掌握羽毛球运动的精髓。",
      category: "badminton",
      categoryText: "羽毛球",
      instructorId: 1,
      instructorName: "张教练",
      maxStudents: 25,
      currentStudents: 8,
      price: 150,
      originalPrice: 200,
      startTime: dayjs().add(1, 'week').format('YYYY-MM-DD 09:00:00'),
      endTime: dayjs().add(1, 'week').add(2, 'hour').format('YYYY-MM-DD 11:00:00'),
      duration: 2,
      location: "体育馆A",
      address: "体育中心体育馆A详细地址1号",
      status: 1,
      statusText: "已发布",
      level: 1,
      levelText: "初级",
      tags: "羽毛球,基础培训,运动",
      coverImage: "",
      content: "培训内容包括：\n1. 羽毛球运动基础知识\n2. 正确的握拍方式和基本姿势\n3. 基本步法训练\n4. 发球技巧（高远球、网前球）\n5. 接球技巧和反应训练\n6. 基本战术和比赛规则\n7. 实战练习和技能巩固",
      requirements: "报名要求：\n1. 年龄在12-60岁之间\n2. 身体健康，无心脏病、高血压等运动禁忌症\n3. 具备基本的运动能力\n4. 需自备运动服装和运动鞋\n5. 培训期间需遵守场馆规定",
      objectives: "培训目标：\n1. 掌握羽毛球基本技能和规则\n2. 提高身体协调性和反应能力\n3. 培养良好的运动习惯\n4. 能够进行基础的羽毛球对抗\n5. 为进阶培训打下坚实基础",
      schedule: "课程安排：\n第1节课：基础知识和握拍姿势（30分钟）\n第2节课：基本步法训练（30分钟）\n第3节课：发球技巧练习（30分钟）\n第4节课：接球和反应训练（30分钟）\n第5节课：实战练习和总结（30分钟）",
      materials: "培训材料：\n1. 羽毛球基础教学视频\n2. 技能练习手册\n3. 规则说明书\n4. 训练计划表\n5. 结业证书模板",
      certificate: true,
      remark: "本次培训为小班教学，确保每位学员都能得到充分的指导。培训结束后将颁发结业证书。",
      createdAt: dayjs().subtract(1, 'week').format('YYYY-MM-DD HH:mm:ss'),
      updatedAt: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss')
    };
    trainingDetail.value = mockDetail;
    
    // 实际开发时使用真实接口
    // const { result } = await getTrainingDetail(trainingId);
    // trainingDetail.value = result;
  } catch (error) {
    ElMessage.error("获取培训详情失败");
  } finally {
    loading.value = false;
  }
}

// 返回列表
function goBack() {
  router.push("/training/list");
}

// 编辑培训
function editTraining() {
  router.push(`/training/form?id=${trainingId}`);
}

// 报名培训
async function handleEnroll() {
  try {
    await ElMessageBox.confirm(
      "确认要报名参加此培训吗？",
      "报名确认",
      {
        confirmButtonText: "确认报名",
        cancelButtonText: "取消",
        type: "info"
      }
    );
    
    // 实际开发时调用报名接口
    // await enrollTraining(trainingId);
    ElMessage.success("报名成功");
    
    // 更新当前报名人数
    trainingDetail.value.currentStudents++;
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("报名失败");
    }
  }
}

// 取消报名
async function handleCancelEnroll() {
  try {
    await ElMessageBox.confirm(
      "确认要取消报名吗？",
      "取消报名确认",
      {
        confirmButtonText: "确认取消",
        cancelButtonText: "保留报名",
        type: "warning"
      }
    );
    
    // 实际开发时调用取消报名接口
    // await cancelEnrollment(trainingId);
    ElMessage.success("取消报名成功");
    
    // 更新当前报名人数
    trainingDetail.value.currentStudents--;
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error("取消报名失败");
    }
  }
}

// 格式化标签
function formatTags(tags: string) {
  return tags ? tags.split(',').filter(tag => tag.trim()) : [];
}

// 格式化内容（换行显示）
function formatContent(content: string) {
  return content ? content.replace(/\\n/g, '\n') : '';
}

onMounted(() => {
  getDetail();
});
</script>

<template>
  <div class="main">
    <div class="mb-4">
      <el-button
        :icon="useRenderIcon(ArrowLeft)"
        @click="goBack"
      >
        返回列表
      </el-button>
      <el-button
        type="primary"
        :icon="useRenderIcon(Edit)"
        @click="editTraining"
      >
        编辑培训
      </el-button>
      <el-button
        type="success"
        :icon="useRenderIcon(UserPlus)"
        @click="handleEnroll"
        :disabled="trainingDetail.currentStudents >= trainingDetail.maxStudents"
      >
        报名培训
      </el-button>
      <el-button
        type="warning"
        :icon="useRenderIcon(UserMinus)"
        @click="handleCancelEnroll"
      >
        取消报名
      </el-button>
    </div>

    <el-card v-loading="loading" class="box-card">
      <template #header>
        <div class="card-header">
          <span class="text-lg font-bold">培训详情</span>
          <el-tag :type="trainingDetail.status === 1 ? 'success' : 'info'">
            {{ trainingDetail.statusText }}
          </el-tag>
        </div>
      </template>

      <div class="training-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3 class="section-title">基本信息</h3>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">培训标题：</span>
                <span class="value">{{ trainingDetail.title }}</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">培训分类：</span>
                <span class="value">{{ trainingDetail.categoryText }}</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">讲师姓名：</span>
                <span class="value">{{ trainingDetail.instructorName }}</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">培训级别：</span>
                <span class="value">{{ trainingDetail.levelText }}</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">培训价格：</span>
                <span class="value price">￥{{ trainingDetail.price }}</span>
                <span v-if="trainingDetail.originalPrice > trainingDetail.price" class="original-price">
                  ￥{{ trainingDetail.originalPrice }}
                </span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">培训时长：</span>
                <span class="value">{{ trainingDetail.duration }} 小时</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">报名人数：</span>
                <span class="value">{{ trainingDetail.currentStudents }}/{{ trainingDetail.maxStudents }}</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">颁发证书：</span>
                <span class="value">
                  <el-tag :type="trainingDetail.certificate ? 'success' : 'info'" size="small">
                    {{ trainingDetail.certificate ? '是' : '否' }}
                  </el-tag>
                </span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 时间地点 -->
        <div class="detail-section">
          <h3 class="section-title">时间地点</h3>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">开始时间：</span>
                <span class="value">{{ trainingDetail.startTime }}</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">结束时间：</span>
                <span class="value">{{ trainingDetail.endTime }}</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">培训地点：</span>
                <span class="value">{{ trainingDetail.location }}</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">详细地址：</span>
                <span class="value">{{ trainingDetail.address }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <!-- 标签 -->
        <div v-if="trainingDetail.tags" class="detail-section">
          <h3 class="section-title">标签</h3>
          <div class="tags-container">
            <el-tag
              v-for="tag in formatTags(trainingDetail.tags)"
              :key="tag"
              class="tag-item"
              size="small"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>

        <!-- 培训描述 -->
        <div class="detail-section">
          <h3 class="section-title">培训描述</h3>
          <div class="content-text">
            {{ trainingDetail.description }}
          </div>
        </div>

        <!-- 培训内容 -->
        <div v-if="trainingDetail.content" class="detail-section">
          <h3 class="section-title">培训内容</h3>
          <div class="content-text">
            <pre>{{ formatContent(trainingDetail.content) }}</pre>
          </div>
        </div>

        <!-- 报名要求 -->
        <div v-if="trainingDetail.requirements" class="detail-section">
          <h3 class="section-title">报名要求</h3>
          <div class="content-text">
            <pre>{{ formatContent(trainingDetail.requirements) }}</pre>
          </div>
        </div>

        <!-- 培训目标 -->
        <div v-if="trainingDetail.objectives" class="detail-section">
          <h3 class="section-title">培训目标</h3>
          <div class="content-text">
            <pre>{{ formatContent(trainingDetail.objectives) }}</pre>
          </div>
        </div>

        <!-- 课程安排 -->
        <div v-if="trainingDetail.schedule" class="detail-section">
          <h3 class="section-title">课程安排</h3>
          <div class="content-text">
            <pre>{{ formatContent(trainingDetail.schedule) }}</pre>
          </div>
        </div>

        <!-- 培训材料 -->
        <div v-if="trainingDetail.materials" class="detail-section">
          <h3 class="section-title">培训材料</h3>
          <div class="content-text">
            <pre>{{ formatContent(trainingDetail.materials) }}</pre>
          </div>
        </div>

        <!-- 备注 -->
        <div v-if="trainingDetail.remark" class="detail-section">
          <h3 class="section-title">备注</h3>
          <div class="content-text">
            {{ trainingDetail.remark }}
          </div>
        </div>

        <!-- 创建信息 -->
        <div class="detail-section">
          <h3 class="section-title">创建信息</h3>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ trainingDetail.createdAt }}</span>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12">
              <div class="detail-item">
                <span class="label">更新时间：</span>
                <span class="value">{{ trainingDetail.updatedAt }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.training-detail {
  .detail-section {
    margin-bottom: 30px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 15px;
      padding-bottom: 8px;
      border-bottom: 2px solid var(--el-color-primary);
    }
    
    .detail-item {
      margin-bottom: 12px;
      display: flex;
      align-items: center;
      
      .label {
        font-weight: 500;
        color: var(--el-text-color-regular);
        min-width: 100px;
        margin-right: 10px;
      }
      
      .value {
        color: var(--el-text-color-primary);
        
        &.price {
          color: var(--el-color-danger);
          font-weight: 600;
          font-size: 16px;
        }
      }
      
      .original-price {
        margin-left: 8px;
        color: var(--el-text-color-placeholder);
        text-decoration: line-through;
        font-size: 14px;
      }
    }
    
    .content-text {
      color: var(--el-text-color-primary);
      line-height: 1.6;
      
      pre {
        white-space: pre-wrap;
        word-wrap: break-word;
        font-family: inherit;
        margin: 0;
      }
    }
    
    .tags-container {
      .tag-item {
        margin-right: 8px;
        margin-bottom: 8px;
      }
    }
  }
}
</style